#!/bin/bash

set -e
set -x

dir="${1}"
shift 1
description="${1}"
shift 1

set +e

name="${1:-$dir}"
shift 1

lib="$(echo ${name} | sed s/-/_/g)"

python_version="${1:-^3.8}"
shift 1

year="${year:-$(date +%Y)}"
license="${1:-MIT}"
shift 1

author="${1:-Shawn Presser}"
author_short="${1:-Shawn}"
shift 1

email="${1:-shawnpresser@gmail.com}"
shift 1

# Personal website
website="${1:-https://www.shawwn.com}"
webname="${1:-shawwn.com}"
shift 1

# GitHub username
github="${1:-shawwn}"
shift 1

# Twitter username
twitter="${1:-theshawwn}"
shift 1

# Hacker News username
hn="${1:-sillysaurusx}"
shift 1

# Patreon username
patreon="${1:-shawwn}"
shift 1

set -e

poetry new --name "$name" "$dir" --src 
cd "$dir"
rm -f pyproject.toml
poetry init --name "$name" --description "$description" --author "$author <${email}>" --python "$python_version" --license "$license" --dev-dependency "pytest" --dev-dependency "pytest-cov" --dev-dependency "python-semantic-release" --no-interaction
git init
#mv README.rst README.md
rm -f README.rst
cat > README.md << EOF
# ${name}

> ${description}

WARNING: This repo is in development. It was automatically generated with [mkpylib](https://github.com/shawwn/scrap/blob/master/mkpylib). If you're reading this message, it means that I use this repo for my own purposes right now. It might not do anything at all; the default functionality is \`print('TODO')\`.

If you really want to try it out, feel free. I recommend reading through the [tests](/tests/test_basic.py) and commit history to see if it does what you need, or [ask me](#contact) for status updates.

Stay tuned!

## Install

\`\`\`
pip3 install -U ${name}
\`\`\`

Or develop locally:

\`\`\`
git clone https://github.com/${github}/${dir} ~/${dir}
cd ~/${dir}
python3 setup.py develop
\`\`\`

## Usage

\`\`\`py
import ${lib}

print('TODO')
\`\`\`

## License

${license}. See [LICENSE](/LICENSE) file.

## Contact

A library by [${author}](${website}). If you found it useful, please consider [joining my patreon](https://www.patreon.com/${patreon})!

My Twitter DMs are always open; you should [send me one](https://twitter.com/${twitter})! It's the best way to reach me, and I'm always happy to hear from you.

- Twitter: [@${twitter}](https://twitter.com/${twitter})
- Patreon: [https://www.patreon.com/${patreon}](https://www.patreon.com/${patreon})
- HN: [${hn}](https://news.ycombinator.com/threads?id=${hn})
- Website: [${webname}](${website})

EOF

if [ "$license" == "MIT" ]
then
cat > LICENSE <<EOF
Copyright (C) ${year} ${author}. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

[ MIT license: http://www.opensource.org/licenses/mit-license.php ]
EOF
fi

cat > .gitignore <<'EOF'
__pycache__
/.idea
/venv/
*.egg-info
/.eggs/
/build/
/dist/
.env
# setup.py # actually, commit the stub setup.py file so that users can pip3 install -e .
.hypothesis/
# /poetry.lock # actually, commit poetry.lock
EOF

# generate a setup.py file so that `python3 -m install -e .` works.
# https://github.com/python-poetry/poetry/discussions/1135#discussioncomment-145763

# add setuptools to build-system requirements.
# TODO: figure out the not-cursed way to do this.
cat pyproject.toml \
 `#| sed 's/"setuptools", //'` \
 `#| sed 's/requires = [\[]\(.*\)[]]/requires = ["setuptools", \1]/g'` \
 `| sed "s/\(version.*\)/\1\nhomepage = \"https:\/\/github.com\/${github}\/${dir}\"/"` \
 | grep -v 'include = ' > pyproject.toml.tmp

cat >> pyproject.toml.tmp <<EOF

[tool.poetry.urls]
"${author_short}'s Website" = "${website}"
"Support me on Patreon" = "https://www.patreon.com/${patreon}"
"@${twitter} on Twitter" = "https://www.twitter.com/${twitter}"
"${hn} on Hacker News" = "https://news.ycombinator.com/threads?id=${hn}"

[tool.semantic_release]
version_toml = "pyproject.toml:tool.poetry.version"
branch = "main"
include_additional_files = "setup.py"
major_on_zero = false
build_command = "poetry build"              # build dists
dist_path = "dist/"                         # where to put dists
upload_to_pypi = false                      # don't auto-upload to PyPI
remove_dist = false                         # don't remove dists
EOF

mv pyproject.toml.tmp pyproject.toml

cat >> src/${lib}/__init__.py <<EOF
# read version from installed package
from importlib.metadata import version
__version__ = version(__name__)
del version
EOF

cat >> tests/test_basic.py <<EOF
import unittest

import ${lib}

class TestCase(unittest.TestCase):
  def test_basic(self):
    self.assertEqual(1, 1)

if __name__ == '__main__':
  unittest.main()
EOF

# update the poetry.lock file.
poetry update

# produce a setup.py file
poetry build --format sdist
tar -xvf dist/*-`poetry version -s`.tar.gz -O '*/setup.py' > setup.py

# uninstall any existing version
python3 -m pip uninstall "${name}" -y

# install it locally, for development
# python3 -m pip install -e .
python3 setup.py develop

# update setup.py file
poetry-gen-setup-py

git add .
git commit -m "Initial commit"

# try an initial publish. (It's impossible to know ahead of time
# whether any given name is forbidden on PyPi; no such API exists,
# so this is the best we can do.
poetry build
# poetry publish

cat <<EOF

# automatically create a private github repo. Set private=1 to make
# the repo private.
hub create "$dir" --description "$description" ${private+--private}

# to make the repo public:
#
#   hub api -Fvisibility=public -XPATCH "/repos/${github}/${dir}" -H 'Accept:application/vnd.github.nebula-preview+json'

git push --set-upstream origin main
EOF
